# -*- coding: utf-8 -*-
import scrapy
import json
from scrapy import Request
from zhihu_user.items import ZhihuUserItem


class ZhihuSpider(scrapy.Spider):
    name = 'zhihu'
    allowed_domains = ['www.zhihu.com']
    start_urls = ['http://www.zhihu.com/']
    followers_url = 'https://www.zhihu.com/api/v4/members/{user}/followers?include={include}&offset={offset}&limit={limit}'
    followees_url = 'https://www.zhihu.com/api/v4/members/{user}/followees?include={include}&offset={offset}&limit={limit}'
    user_url = 'https://www.zhihu.com/api/v4/members/{user}?include={include}'
    followers_data = 'data[*].answer_count,articles_count,gender,follower_count,is_followed,is_following,badge[?(type=best_answerer)].topics'
    user_data = 'allow_message,is_followed,is_following,is_org,is_blocking,employments,answer_count,follower_count,articles_count,gender,badge[?(type=best_answerer)].topics'
    start_user = 'excited-vczh'
    offset = 0
    limit = 20

    def start_requests(self):
        yield Request(url=self.user_url.format(user=self.start_user, include=self.user_data), callback=self.parse_user)

    def parse_followers(self, response):
        results = json.loads(response.text)
        if 'data' in results.keys():
            for result in results.get('data'):
                yield Request(url=self.user_url.format(user=result.get('url_token'), include=self.user_data), callback=self.parse_user)
        if 'paging' in results.keys() and results.get('paging').get('is_end') is False:
            next_page = results.get('paging').get('next')
            yield Request(url=next_page, callback=self.parse_followers)

    def parse_followees(self, response):
        results = json.loads(response.text)
        if 'data' in results.keys():
            for result in results.get('data'):
                yield Request(url=self.user_url.format(user=result.get('url_token'), include=self.user_data), callback=self.parse_user)
        if 'paging' in results.keys() and results.get('paging').get('is_end') is False:
            next_page = results.get('paging').get('next')
            yield Request(url=next_page, callback=self.parse_followees)

    def parse_user(self, response):
        item = ZhihuUserItem()
        result = json.loads(response.text)
        for field in item.fields:
            if field in result.keys():
                item[field] = result.get(field)
        yield item
        url_token = result.get('url_token')
        yield Request(url=self.followers_url.format(user=url_token, include=self.followers_data, offset=self.offset, limit=self.limit), callback=self.parse_followers)
        yield Request(url=self.followees_url.format(user=url_token, include=self.followers_data, offset=self.offset, limit=self.limit), callback=self.parse_followees)

